package violin.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import javax.ws.rs.PathParam;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;

public class HttpParamsCollector {
    private final Class<?>[] parameterTypes;
    private final Annotation[][] parameterAnnotations;
    private final Map<String, String> pathParams;

    public HttpParamsCollector(Method handlerMethod, Map<String, String> pathParams) {
        this.parameterTypes = handlerMethod.getParameterTypes();
        this.parameterAnnotations = handlerMethod.getParameterAnnotations();
        this.pathParams = pathParams;
    }

    public HttpParamsCollector collect(HttpServletRequest httpServletRequest) {
        Map<String, Object> requestParams = extractRequestParams(httpServletRequest);
        Map<String, Object> sessionParams = extractSessionParams(httpServletRequest.getSession());
        Map<String, Object> cookieParams = extractCookieParams(httpServletRequest.getCookies());

        return this;
    }

    private Map<String, Object> extractCookieParams(Cookie[] cookies) {
        return null;
    }

    private Map<String, Object> extractSessionParams(HttpSession session) {
        return null;
    }

    private Map<String, Object> extractRequestParams(HttpServletRequest httpServletRequest) {
        return httpServletRequest.getParameterMap();
    }
     //get parameter Annotations of method
    public Object[] params() {
        Object[] params = new Object[parameterTypes.length];
        for (int i = 0, index = params.length; i < index; i++) {
            Annotation[] parameterAnnotation = parameterAnnotations[i];
            for (Annotation annotation : parameterAnnotation) {
                String value = null;
                if (annotation.annotationType().isAssignableFrom(PathParam.class)) {
                    PathParam param = (PathParam) annotation;
                    value = pathParams.get(param.value());
                }
                if (parameterTypes[i].isAssignableFrom(Long.class)) {
                    params[i] = Long.parseLong(value);
                } else {
                    params[i] = value;
                }
            }
        }
        return params;
    }
}
